<template>
  <div @dragover="dragoverHandle" @dragenter="dragoverHandle" @drop="drop" class="main_container">
    <div
      class="component_item"
      :key="index"
      :style="{
        width: typeof pageItem.width === 'string' ? pageItem.width : pageItem.width + 'px',
        backgroundColor: pageItem.attr.color || 'none',
        height: typeof pageItem.height === 'string' ? pageItem.height : pageItem.height + 'px',
        display: pageItem.boxDisplay ? pageItem.boxDisplay : 'block',
      }"
      v-for="(pageItem, index) in pagedataStore.pageItemList"
    ></div>
  </div>
</template>

<script lang="ts" setup>
  import usePageDataStore from '@/store/pageData';
  import Sortable from 'sortablejs';
  const pagedataStore = usePageDataStore();
  // 拖入组件
  function drop(e: any) {
    let info = JSON.parse(e.dataTransfer.getData('info'));
    if (info) {
      info.position = {
        x: e.offsetX - info.width / 2,
        y: e.offsetY - info.height / 2,
      };
      pagedataStore.add(info);
      console.log(pagedataStore.pageItemList, 333);
    }

    // this.$store.commit('ADD_CHART', chart);
    // this.$store.commit('SET_CURRENT_CHART_INDEX', this.chartList.length - 1);
  }
  // 阻止默认事件
  function dragoverHandle(e: any) {
    e.preventDefault();
  }
  function dragSort(dom: HTMLElement) {
    new Sortable(dom, {
      animation: 150,
      ghostClass: 'drag-ghost-class',
    });
  }
  onMounted(() => {
    nextTick(() => {
      let container: HTMLElement | null = document.querySelector('.main_container');
      if (container) {
        dragSort(container);
      }
    });
  });
</script>

<style scoped lang="scss">
  .main_container {
    margin: 40px auto;
    width: 375px;
    height: 700px;
    border: 1px solid $border-primary;
    font-size: 0;
  }
  .component_item {
    display: inline-block;
    background-color: red;
    margin-bottom: 0;
    cursor: pointer;
  }
  .drag-ghost-class {
    background-color: rgba($color: blue, $alpha: 0.1);
  }
</style>
